package cn.edu.zjgsu.ito.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.InputMismatchException;

import cn.edu.zjgsu.ito.service.ServiceFactory;
import cn.edu.zjgsu.ito.service.StudentExportPdfService;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.server.Scanner;

public class StudentExportPdfController extends Controller {
	
	StudentExportPdfService studentExportPdfService = ServiceFactory.createStudentExportPdfService();
	
	public void index(){

		String passportNo = getSessionAttr("passportNo");
		
		OutputStream out = null;
		Date date = new Date();
		DateFormat formatter=new SimpleDateFormat("yyyyMMddhhmmss");
		String time=formatter.format(date);
		String filedir = PathKit.getWebRootPath();
		filedir = filedir + "\\WEB-INF\\download\\";
		System.out.println("------1------");
        deleteFile(new File(filedir));//清空缓存区
		String temp = passportNo + "成绩" + time +".pdf";
		String outpath = filedir + temp;
		
		try {
			System.out.println(outpath);
			out = new FileOutputStream(outpath);
			studentExportPdfService.createPdf(out,passportNo);
			String newOutPath = filedir + passportNo + "成绩单" + time +".pdf";
			studentExportPdfService.addWater(outpath,newOutPath);
			renderFile(new File(newOutPath));
			System.out.println("结束");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	 		
		
		
	}
	
	public void deleteFile(File oldPath) {
        if (oldPath.isDirectory()) {
         File[] files = oldPath.listFiles();
         for (File file : files) {
           deleteFile(file);
         }
        }else{
          oldPath.delete();
        }
	}
	
	public void deleteNew(String path){
		System.out.println("删除文件路径："+path);
		File file = new File(path);
        File[] files = file.listFiles();
        for(int i=0; i<files.length; i++){
            File tmp = files[i];
            if(tmp.toString().endsWith(".pdf")){
                tmp.delete();
            }
        }
	}
	
	
}
